package cn.virens.web.components.open.wxma.router.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import cn.binarywang.wx.miniapp.api.WxMaUserService;
import cn.virens.web.components.open.session.WxSessionManager;
import cn.virens.web.components.open.wxma.WxMaServiceImpl;
import cn.virens.web.components.open.wxma.router.WxMaRouterRuleHandler;
import cn.virens.web.components.open.wxma.session.WxMaSessionMessage;
import me.chanjar.weixin.common.error.WxErrorException;

/**
 * 公共消息路由父类
 * 
 * @author virens
 */
public abstract class AbstractMessageHandler implements WxMaRouterRuleHandler {
	protected final Logger logger = LoggerFactory.getLogger(getClass());

	protected @Autowired WxMaServiceImpl mWxService;

	@Override
	public final String handle(WxMaSessionMessage wxMessage, WxSessionManager sessionManager) {
		logger.debug("收到来自微信的消息:" + String.valueOf(wxMessage));

		try {
			this.handle0(wxMessage, sessionManager);
		} catch (Exception e) {
			logger.error("微信:" + e.getMessage(), e);
		} finally {
			wxMessage.putSession(sessionManager);
		}

		return "success";
	}

	/**
	 * 路由处理
	 * 
	 * @param  wxMessage        消息体
	 * @param  sessionManager   session管理器
	 * @return
	 * @throws WxErrorException
	 */
	protected void handle0(WxMaSessionMessage wxMessage, WxSessionManager sessionManager) throws Exception {
	}

	/**
	 * 获取用户管理服务
	 * 
	 * @return
	 */
	protected WxMaUserService getUserService() {
		return mWxService.getUserService();
	}

}
